package com.hub.realtime.resource;


import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.CopyOnWriteArraySet;

@ServerEndpoint(value = "/websocket")
@Component
public class WebSocketTest {

    // 静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;
    private Timer timer = new Timer();
    // concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
    private static CopyOnWriteArraySet<WebSocketTest> webSocketSet = new CopyOnWriteArraySet<WebSocketTest>();
    private Session session;
    private static Map<String, WebSocketTest> webSocketMap = new HashMap<>();

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session) {

        this.session=session;
        webSocketSet.add(this);
        System.out.println("有新的连接，总数"+ webSocketSet.size() );
        timer.schedule(new TimerTask() {
            public void run() {
                sendMessage();
            }
        }, 3000, 1000);

    }


    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        timer.cancel();
        webSocketSet.remove(this); // 从set中删除

        System.out.println("有一连接关闭！当前在线人数为");
    }

    /**
     * 发生错误时调用
     *
     */
    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("发生错误");
        error.printStackTrace();
    }

    public void sendMessage()  {
        try {
            this.session.getBasicRemote().sendText("123333333333333");
        } catch (IOException e) {
            e.printStackTrace();
        }
        // this.session.getAsyncRemote().sendText(message);
    }

}

